using UnityEngine;

public class TankCtrl : RoleInfo
{
    public float moveSpeed = 5f;  // 移动速度
    public float rotateSpeed = 50f; // 旋转速度
    private Rigidbody rigi; // 刚体控制器
    public Collider coll;
    public Animator anim; // 动画控制器
    public bool isDead = false; // 是否死亡
    public int weaponID = 0;
    public float[] fireRate = new float[1]; // 射击频率
    public float FireDTime = 0f; // 下一次射击的时间
    private bool isFiring = false; // 是否正在发射子弹

    new void Start()
    {
        base.Start();
        rigi = GetComponent<Rigidbody>(); // 获取刚体组件
        coll = GetComponent<Collider>();

        // 确保重力启用
        rigi.useGravity = true;
    }

    void Update()
    {
        if (isDead) return;
        if (rigi) Move();

        // 处理射击
        if (Input.GetMouseButtonDown(0)) isFiring = true;
        if (Input.GetMouseButtonUp(0)) isFiring = false;

        if (FireDTime <= 0)
        {
            if (isFiring)
            {
                BroadcastMessage("Fire");
                FireDTime = fireRate[weaponID];
                if (anim) anim.SetTrigger("fire");
            }
        }
        else FireDTime -= Time.deltaTime;
    }

    private void Move()
    {
        // 获取输入
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");

        // Vector3 pos =  transform.right * vertical * moveSpeed* Time.deltaTime;
        // rigi.MovePosition(rigi.position + pos);
        // float turn =  vertical * rotateSpeed* Time.deltaTime;
        // Quaternion rota = Quaternion.Euler(0, turn, 0);
        // rigi.MoveRotation(rigi.rotation * rota);
        // 应用移动
        rigi.velocity = transform.right * vertical * moveSpeed * Time.deltaTime;
        rigi.angularVelocity = transform.up * horizontal * rotateSpeed * Time.deltaTime;

        // 设置动画状态
        // if (moveDirection != Vector3.zero)
        // {
        //     if (anim) anim.SetInteger("state", 1);
        // }
        // else if (anim) anim.SetInteger("state", 0);
    }

    public void die() // 接收 RoleInfo 中发送的 die 事件
    {
        if (anim) anim.SetTrigger("die"); // 播放死亡动画
        isDead = true; // 标记为死亡
        coll.enabled = false; // 关闭碰撞
    }
}